package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.service.OrdersService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单管理
 */
@RestController
@RequestMapping("order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    /**
     * 处理下单的请求
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        ordersService.submit(orders);
        return R.success("下单成功");
    }


    /**
     * 处理移动端分页查询历史订单的请求,包含
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(Integer page, Integer pageSize) {
        Page<OrdersDto> pageInfo = ordersService.userPage(page, pageSize);
        return R.success(pageInfo);
    }

    /**
     * 处理后端订单明细根据订单号分页查询的请求(根据日期查询未完成)
     *
     * @param page
     * @param pageSize
     * @param number
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(Integer page, Integer pageSize, String number, LocalDateTime loginTime, @DateTimeFormat(pattern = "") LocalDateTime endTime) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        ordersService.lambdaQuery()
                .like(!StringUtils.isBlank(number), Orders::getNumber, number)
                .between(loginTime != null && endTime != null, Orders::getOrderTime, loginTime, endTime)
                .page(pageInfo);
        return R.success(pageInfo);
    }

//select *
//from orders
//where order_time between '2022-10-21 20:48:43' AND '2022-10-22 20:48:43';

    /**
     * 处理修改订单状态的请求
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders) {
        ordersService.lambdaUpdate()
                .set(Orders::getStatus, orders.getStatus())
                .eq(Orders::getId, orders.getId())
                .update();
        return R.success("修改成功");
    }


    /**
     * 处理再来一单的请求(未完成)
     *
     * @param id
     * @return
     */
//    @PostMapping("/again")
//    public R<Orders> again(Long id) {
//        Orders order = ordersService.getById(id);
//        return R.success(order);
//    }
}
